/**
 * 搜索页面脚本
 */

// 全局变量
let currentPage = 1
let hasMore = true
let isLoading = false
let searchQuery = ""

document.addEventListener("DOMContentLoaded", () => {
  // 获取搜索关键词
  const urlParams = new URLSearchParams(window.location.search)
  searchQuery = urlParams.get("q") || ""

  // 设置搜索关键词
  const searchQueryElement = document.getElementById("searchQuery")
  if (searchQueryElement) {
    searchQueryElement.textContent = searchQuery
  }

  // 设置搜索输入框
  const searchInput = document.getElementById("searchInput")
  if (searchInput) {
    searchInput.value = searchQuery
  }

  // 初始化搜索结果
  loadSearchResults()

  // 初始化无限滚动
  initInfiniteScroll()
})

/**
 * 加载搜索结果
 * @param {boolean} reset 是否重置
 */
async function loadSearchResults(reset = false) {
  const searchResults = document.getElementById("searchResults")
  const loadingMore = document.getElementById("loadingMore")
  const noResults = document.getElementById("noResults")
  const resultCount = document.getElementById("resultCount")

  if (!searchResults) return

  // 如果没有搜索关键词，显示空状态
  if (!searchQuery) {
    searchResults.innerHTML = `
      <div class="empty-state">
        <i class="ri-search-line"></i>
        <p>请输入搜索关键词</p>
      </div>
    `
    if (resultCount) resultCount.textContent = "0"
    if (noResults) noResults.style.display = "none"
    return
  }

  // 重置列表
  if (reset) {
    searchResults.innerHTML = `
      <div class="media-loading-grid">
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
        <div class="media-skeleton"></div>
      </div>
    `
    currentPage = 1
    hasMore = true
  }

  if (isLoading || !hasMore) return

  isLoading = true
  if (loadingMore) loadingMore.style.display = "flex"

  try {
    const activeSource = window.AppConfig.getActiveSource()
    if (!activeSource) {
      searchResults.innerHTML = `
        <div class="empty-state">
          <i class="ri-film-line"></i>
          <p>请先添加媒体源</p>
        </div>
      `
      isLoading = false
      if (loadingMore) loadingMore.style.display = "none"
      return
    }

    // 获取搜索结果
    const response = await window.API.getMediaList(activeSource, currentPage, 0, searchQuery)

    // 更新结果数量
    if (resultCount) {
      resultCount.textContent = response.total
    }

    // 清空加载中状态
    if (reset) {
      searchResults.innerHTML = ""
    }

    if (response.list.length === 0 && currentPage === 1) {
      if (noResults) noResults.style.display = "flex"
      hasMore = false
      isLoading = false
      if (loadingMore) loadingMore.style.display = "none"
      return
    } else {
      if (noResults) noResults.style.display = "none"
    }

    // 添加媒体卡片
    response.list.forEach((item) => {
      const card = window.UI.createMediaCard(item)
      searchResults.appendChild(card)
    })

    // 更新分页状态
    hasMore = response.page < response.pagecount
    currentPage++
  } catch (error) {
    console.error("搜索失败:", error)
    if (currentPage === 1) {
      searchResults.innerHTML = `
        <div class="error-state">
          <i class="ri-error-warning-line"></i>
          <p>搜索失败，请重试</p>
        </div>
      `
    }
  } finally {
    isLoading = false
    if (loadingMore) loadingMore.style.display = hasMore ? "flex" : "none"
  }
}

/**
 * 初始化无限滚动
 */
function initInfiniteScroll() {
  const loadingMore = document.getElementById("loadingMore")
  if (!loadingMore) return

  // 创建交叉观察器
  const observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting && !isLoading && hasMore) {
        loadSearchResults()
      }
    },
    { threshold: 0.1 },
  )

  // 观察加载更多元素
  observer.observe(loadingMore)
}

/**
 * 格式化时间为相对时间
 * @param {number} timestamp 时间戳
 * @returns {string} 相对时间
 */
function formatTimeAgo(timestamp) {
  const now = Date.now()
  const diff = now - timestamp

  // 小于1分钟
  if (diff < 60 * 1000) {
    return "刚刚"
  }

  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }

  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }

  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }

  // 大于30天
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
}
